const base = require("./../base");

module.exports = class extends base {
    async _initialize() {
        await super.isWxaAuth();
        await super.isShopAuth();
    }

    /**
     *
     * @api {get} /shop/api/shop/search/index 商品搜索
     * @apiDescription 商品搜索
     * @apiGroup Shop/api
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} Referer 小程序referer.
     *
     * @apiParam {String} keyword     商品名称
     * @apiParam {Number} groupId     分组id
     * @apiParam {String} orderBy     排序字段（"id":商品id ， "sale":销量 ，"rank":排序号）
     * @apiParam {String} orderType   排序（"desc":降序，"asc":升序）
     * @apiParam {Number} page        页码
     *
     * @apiSampleRequest /shop/api/shop/search/index
     *
     */
    async index() {
        const {
            keyword,
            page = 1,
            groupId,
            orderBy = "rank",
            orderType = "desc"
        } = this.query;
        const shopId = this.state.shop.id;

        const product = await this.model("product")
            .query(qb => {
                if (groupId) {
                    qb.join(
                        "shop_productgroup_product",
                        "shop_productgroup_product.product_id",
                        "shop_product.id"
                    );
                    qb.where("productgroup_product.group_id", groupId);
                }

                if (keyword) {
                    qb.where("shop_product.name", "like", `%${keyword}%`);
                }

                qb.orderBy(orderBy, orderType);
                qb.where("shop_product.status", "=", 1);
                qb.where("shop_product.shop_id", "=", shopId);
            })
            .fetchPage({
                page
            });
        this.success(product);
    }
};
